﻿using Spring.Context;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dubbo.Config.Spring
{
    public class SpringExtensionFactory
    {
        private static readonly ConcurrentDictionary<IApplicationContext, byte> contexts = new ConcurrentDictionary<IApplicationContext, byte>();

        public static void AddApplicationContext(IApplicationContext context)
        {
            contexts.AddOrUpdate(context, (byte)0, (k, v) => (byte)0);
        }

        public static void RemoveApplicationContext(IApplicationContext context)
        {
            byte value;
            contexts.TryRemove(context, out value);
        }
        
        public T GetExtension<T>(string name)
        {
            foreach (IApplicationContext context in contexts.Keys)
            {
                if (context.ContainsObject(name))
                {
                    object obj = context.GetObject(name);
                    if (obj is T)
                    {
                        return (T)obj;
                    }
                }
            }
            return default(T);
        }
    }
}
